package com.example.demo.controller;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.common.Result;
import com.example.demo.entity.SessionStorage;
import com.example.demo.entity.SysLoginRecord;
import com.example.demo.entity.SysUser;
import com.example.demo.judge.main.JudgeService;
import com.example.demo.service.SysLoginRecordService;
import com.example.demo.service.SysUserService;
import com.example.demo.utils.IpUtils;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.UserInfoUtil;
import com.example.demo.utils.enu.UserInfoEnu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author ld&zjw
 * @since 2024-01-27
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysLoginRecordService loginRecordService;
    @Autowired
    JudgeService judgeService;
    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/login")
    public Result<?> login(@RequestBody SysUser user, HttpServletRequest request) {
        SysUser res = sysUserService.login(user);
        if (res == null) return Result.error("-1", "用户名或密码错误！");
        else {
            SessionStorage sessionStorage = new SessionStorage();
            sessionStorage.setId(res.getId());
            sessionStorage.setUsername(res.getUsername());
            sessionStorage.setAge(res.getAge());
            sessionStorage.setRole(res.getRole());
            sessionStorage.setAddress(res.getAddress());
            sessionStorage.setNickName(res.getNickName());
            sessionStorage.setSpare1(res.getSpare1());
            sessionStorage.setSpare2(res.getSpare2());
            sessionStorage.setSpare3(res.getSpare3());
            sessionStorage.setSpare4(res.getSpare4());
            sessionStorage.setSpare5(res.getSpare5());
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.HOUR_OF_DAY, 12);
            Map<String, String> map = new HashMap<>();
            map.put("userId", String.valueOf(res.getId()));
            map.put("username", res.getUsername());
            map.put("role", String.valueOf(res.getRole()));
            String token = JWTUtil.getToken(map);
            sessionStorage.setToken(token);
            redisUtil.set(MessageFormat.format("SessionStorage_{0}_{1}", new Object[]{sessionStorage.getId(), sessionStorage.getUsername()}), sessionStorage, 43200000L);
            SysLoginRecord sysLoginRecord = new SysLoginRecord();
            sysLoginRecord.setUsername(user.getUsername());
            sysLoginRecord.setLoginIp(IpUtils.getIpAddr(request));
            sysLoginRecord.setLoginTime(new Date());
            loginRecordService.save(sysLoginRecord);
            return Result.success(sessionStorage);
        }
    }

    @PostMapping("/register")
    public Result<?> register(@RequestBody SysUser user) {
        Boolean res = sysUserService.register(user);
        if (res) return Result.success();
        else return Result.error("-1", "用户名已存在!");
    }

    @GetMapping("/logout")
    public Result<?> logout() {
        String userId = UserInfoUtil.get(UserInfoEnu.userId.getCode());
        String userName = UserInfoUtil.get(UserInfoEnu.username.getCode());
        redisUtil.del(MessageFormat.format("SessionStorage_{0}_{1}", new Object[]{userId, userName}));
        return Result.success();
    }

    @PostMapping
    public Result<?> save(@RequestBody SysUser user) {
        return Result.success(sysUserService.save(user));
    }

    @PutMapping
    public Result<?> update(@RequestBody SysUser user) {
        return Result.success(sysUserService.update(user));
    }

    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        return Result.success(sysUserService.update(id));
    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id) {
        return Result.success(sysUserService.getById(id));
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "") String search) {
        return Result.success(sysUserService.findPage(pageNum, pageSize, search));
    }


}

